package com.gzhu.knowledgeAdmin.service.impl;


import com.gzhu.knowledgeAdmin.common.dto.type.TypeAddRequest;
import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.repository.TemplateTypeRepository;
import com.gzhu.knowledgeAdmin.entity.TemplateType;
import com.gzhu.knowledgeAdmin.service.TemplateTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TemplateTypeServiceImpl implements TemplateTypeService {

    @Autowired
    private TemplateTypeRepository templateTypeRepository;

    @Override
    public List<String> getTypeList() {

        List<TemplateType> templateTypeList = templateTypeRepository.findAll();

        return templateTypeList.stream().map(TemplateType::getName).collect(Collectors.toList());
    }

    @Override
    public List<TemplateType> getAllTypeList() {
        return templateTypeRepository.findAll();
    }

    @Override
    public void addType(TypeAddRequest typeAddRequest) {
        String typeName = typeAddRequest.getName();

        TemplateType templateType = templateTypeRepository.getTemplateTypeByName(typeName);

        if (templateType != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"类型已经存在");
        }

        templateType = new TemplateType();
        templateType.setName(typeName);

        templateTypeRepository.save(templateType);
    }

    @Override
    public void deleteType(List<Integer> idList) {
        try {
            templateTypeRepository.deleteAllByIdInBatch(idList);
        } catch (EmptyResultDataAccessException e) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"id不存在!");
        }

    }

}
